from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings


# 用户表 包含学生和老师
class Userinfo(AbstractUser):
    role_type = (
        (0, '学生'),
        (1, '老师'),
        (2, '管理员'),
    )
    mobile = models.CharField(max_length=11, null=True, blank=True, verbose_name='用户手机号')
    icon = models.FileField(upload_to='icon/', default='icon/default.png')
    role = models.SmallIntegerField(choices=role_type, default=0, verbose_name="用户角色")
    student_class = models.ForeignKey("StudentClass", on_delete=models.SET_NULL, db_constraint=False, null=True,
                                      blank=True, verbose_name="所属班级", related_name='studentClass')

    class Meta:
        db_table = 'user'  # 指定表名
        verbose_name_plural = '用户表'

    def __str__(self):
        return self.username

    def class_name(self):
        try:
            return self.student_class.name
        except Exception:
            return ''

    def paper_count(self):
        return self.studentPaper.count()

    def join_time(self):
        return self.date_joined.strftime('%Y-%m-%d %H:%M:%S')

    def role_name(self):
        return self.get_role_display()

    def icon_url(self):
        return settings.HOST_URL + settings.MEDIA_URL + str(self.icon)


# 班级表
class StudentClass(models.Model):
    name = models.CharField(max_length=64, unique=True, null=False, verbose_name='班级名称')
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    students = models.IntegerField(verbose_name="学生人数", default=0)

    class Meta:
        db_table = 'studentclass'  # 指定表名
        verbose_name_plural = '班级表'

    def __str__(self):
        return self.name

    def time(self):
        return self.create_time.strftime("%Y-%m-%d %H:%M:%S")

    def count(self):
        return self.studentClass.count()
